package com.google.code.japndroid;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;

public class PacketKillerMasterSyncAutomaticallyReciever extends BroadcastReceiver {
	
	@Override
	public void onReceive(Context context, Intent intent) {
		
		Intent serviceIntent = new Intent(context,PacketKillerMasterSyncAutomaticallyService.class);
		
		if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) ){
	        boolean isOn = android.content.ContentResolver.getMasterSyncAutomatically();

	        // 自動同期がONならインターバルサービスを起動する
			if( isOn ){
				context.startService(serviceIntent);
			}
		}else{
			Bundle extras = intent.getExtras();
			boolean isEnabled = extras.getBoolean("enable");
		  	android.content.ContentResolver.setMasterSyncAutomatically(isEnabled);
			// DONE intent を投げる
			Intent message = new Intent(PacketKillerConstants.MASTER_SYNCAUTOMATICALLY_CHANGE_DONE);
			context.sendBroadcast(message);
			
		  	// ONになったので、インターバルの設定が有効ならサービスをきどうする
			if( isEnabled ){
				SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(context);
				long wk = Long.parseLong(preference.getString("pref_itvl_value","0"));
				if( wk > 0L ){
					context.startService(serviceIntent);
				}
			}else{
				context.stopService(serviceIntent);
			}
			Log.v("PACKET KILLER","RECIEVER is MASTER SYNC AUTOMATICALLY　(enable:" + isEnabled + ")");
		}
	}
}
